﻿using System;
using System.Data;
using System.Reflection;
using System.Text;
using ICarPool.ORM.Attributes;
using ICarPool.ORM.DBUtility;
using System.Collections;

namespace ICarPool.ORM.Common
{
    public class DbEntityUtils
    {
        private static Hashtable tableInfoCache = new Hashtable();

        #region 获取tableinfo
        /// <summary>
        /// 获取实体类对应的表明
        /// </summary>
        /// <param name="classType"></param>
        /// <returns></returns>
        public static string GetTableName(Type classType)
        {
            object classAttr = classType.GetCustomAttributes(false)[0];
            TableAttribute tableAttr = classAttr as TableAttribute;
           
            if (tableAttr == null)
            {
                throw new Exception("实体类:" + classType.FullName + "的属性配置[Table(name=\"tablename\")]错误或未配置");
            }

            return tableAttr.Name;
        }

        //public static string GetPrimaryKey(object attribute)
        //{
        //    string strPrimary = string.Empty;
        //    IdAttribute attr = attribute as IdAttribute;
        //    switch (attr.Strategy)
        //    {
        //        case GenerationType.INDENTITY:
        //            break;
        //        case GenerationType.SEQUENCE:
        //            strPrimary = System.Guid.NewGuid().ToString();
        //            break;
        //        case GenerationType.TABLE:
        //            break;
        //    }

        //    return strPrimary;
        //}

        //public static string GetColumnName(object attribute)
        //{
        //    string columnName = string.Empty;
        //    if (attribute is ColumnAttribute)
        //    {
        //        ColumnAttribute columnAttr = attribute as ColumnAttribute;
        //        columnName = columnAttr.Name;
        //    }
        //    if (attribute is IdAttribute)
        //    {
        //        IdAttribute idAttr = attribute as IdAttribute;
        //        columnName = idAttr.Name;
        //    }

        //    return columnName;
        //}

        /// <summary>
        ///  获取对象的属性信息，以用于生成增删改的sql
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="dbOpType"></param>
        /// <returns></returns>
        public static TableInfo GetTableInfo(object entity, DbOperateType dbOpType)
        {
            TableInfo tableInfo = new TableInfo();
            Type type = entity.GetType();

            tableInfo.TableName = GetTableName(type);
            PropertyInfo[] properties = ReflectionUtils.GetProperties(type);
           
            foreach (PropertyInfo property in properties)
            {
                object propvalue = ReflectionUtils.GetPropertyValue(entity, property);;
                object[] propertyAttrs = property.GetCustomAttributes(false);

                //如果该属性，被标记为表中的列
                if (propertyAttrs.Length != 0)
                {
                    ColumnAttribute columnAttr = propertyAttrs[0] as ColumnAttribute;

                    //除Insert时IsInsert=false 或者Update时 isupdate=false 情况外，都加入到Columns中
                    if (columnAttr != null
                        && (
                             (dbOpType == DbOperateType.INSERT && columnAttr.IsInsert) 
                             || (dbOpType == DbOperateType.UPDATE && columnAttr.IsUpdate)
                             ||dbOpType == DbOperateType.DELETE
                           )
                       )
                    {
                        tableInfo.Columns.Put(property.Name, propvalue);
                    }
                }
            }

            return tableInfo;
        }

        /// <summary>
        /// 获取对象的属性信息，以用于生成查询的sql。
        /// </summary>
        /// <param name="classType"></param>
        /// <returns></returns>
        public static TableInfo GetTableInfo(Type classType)
        {
            if (!tableInfoCache.ContainsKey(classType))
            {
                TableInfo tableInfo = new TableInfo();

                tableInfo.TableName = GetTableName(classType);
                PropertyInfo[] properties = ReflectionUtils.GetProperties(classType);

                foreach (PropertyInfo property in properties)
                {
                    //判断该属性是否有自定义的ColumnAttribute
                    if (property.GetCustomAttributes(false).Length != 0)
                    {
                        //做查询时，不需要属性的值，故添加入null
                        tableInfo.Columns.Put(property.Name, null);
                    }
                }

                tableInfoCache.Add(classType, tableInfo);
            }
           
            return tableInfoCache[classType] as TableInfo;
        }

        #endregion

        public static void SetParameters(ColumnInfo columns, params IDbDataParameter[] parms)
        {
            int i = 0;
            foreach (string key in columns.Keys)
            {
                parms[i].ParameterName = key;
                parms[i].Value = columns[key] ?? DBNull.Value;
                i++;
            }
        }
    }
}
